/*
 * 
 * Copyright 2010 David H Pollack
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * 
 */

package com.dhpollack.rotogss.servlets;

import java.io.IOException;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.oauth.OAuthException;

import com.dhpollack.rotogss.data.AppConfig;
import com.dhpollack.rotogss.data.RotoGSSUsers;
import com.dhpollack.rotogss.helper.AppHelper;
import com.dhpollack.rotogss.helper.PMF;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.simpleyql.Api;
import com.simpleyql.ApiFactory;
import com.simpleyql.QueryResult;

/**
 * @author davidpl
 *
 */
public class YahooGetGamesServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 5454199452876670251L;
	
	private AppConfig APP_CONFIG = AppHelper.get();

    protected void service(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {
		
    	PersistenceManager pm = PMF.get().getPersistenceManager();
    	
    	String user = req.getParameter("user");
		
		String game_keys = req.getParameter("game_keys");

		if(user == null) {
			log("No user set");
			return;
		}
		
		if(game_keys == null) {
			game_keys = "mlb,nba,nhl,nfl";
		}

		RotoGSSUsers rotogss_user;
		Key rotogss_userkey = new KeyFactory.Builder(RotoGSSUsers.class.getSimpleName(),user).getKey();
		try {
			rotogss_user = pm.getObjectById(RotoGSSUsers.class, rotogss_userkey);
		} catch(JDOObjectNotFoundException e) {
			log("No user found for " + user);
			log("Key used: " + rotogss_userkey.toString());
			return;
		}
		
		String YAHOO_CONSUMER_KEY = APP_CONFIG.getYahooConsumerKey();
		String YAHOO_CONSUMER_SECRET = APP_CONFIG.getYahooConsumerSecret();
		String SIMPLEYQL_CALLBACK_SERVLET = APP_CONFIG.getBaseUrl() + "/simpleyqlcallback/";
		
		Api api = ApiFactory.getApiInstance(
				YAHOO_CONSUMER_KEY,
	            YAHOO_CONSUMER_SECRET,
	            SIMPLEYQL_CALLBACK_SERVLET,
	            false, null);
		
		QueryResult qr = null;
		
		StringBuilder yql = new StringBuilder();
		yql.append("http://fantasysports.yahooapis.com/fantasy/v2/users;use_login=1/games;game_keys=");
		yql.append(game_keys);
		yql.append("/leagues");
		yql.append("/teams");
		
		
		String authdata = rotogss_user.getYahooOAuthData();
		
		String yql_string = yql.toString();

		log(rotogss_user.getGoogleUserKey().getName());
		log("Sending following request: \n" + yql_string);
		
		try {
			qr = api.query2(yql_string, authdata);
		} catch (OAuthException e) {
			log("Error posting to Y!:", e);
			return;
		} catch (RuntimeException e) {
			if (e.getMessage().equals("Unable to complete the HTTP request")) {
				if (e.getCause().getMessage()
						.contains("Timeout while fetching")) {
					log("Unable to complete Yahoo! query", e);
				} else {
					log("Error posting to Y!:", e);
					return;
				}
			} else {
				throw e;
			}
		}
		
		// Update token, if needed (for future requests)
	    if (qr != null && !qr.getAuthdata().equals(rotogss_user.getYahooOAuthData())) {
	    	rotogss_user.setYahooOAuthData(qr.getAuthdata());
	    	try {
	    		pm.makePersistent(rotogss_user);
	    	} finally {
	    		pm.close();
	    	}
	    }
	    
	    if(!pm.isClosed()) {
	    	pm.close();
	    }
	    String xml = qr.getText();
	    log("XML length: " + xml.length());
		req.setAttribute("rotogss.gamesxml", qr.getText());
		req.getRequestDispatcher("/admin/yahooParseGames").include(req, resp);
		
		
		
		
	}

}
